package problem152;

//153.乘积最大子数组
//https://leetcode.cn/problems/maximum-product-subarray/

class Solution2 {
    public int maxProduct(int[] nums) {
        int n = nums.length;
        int[] f = new int[n+1]; //大于0的最大乘积
        int[] g = new int[n+1]; //小于0的最小乘积
        f[0] = 1; g[0] = 1;
        for(int i = 1; i<=n; i++) {
            f[i] = Math.max(Math.max(nums[i-1], f[i-1]*nums[i-1]), g[i-1]*nums[i-1]);
            g[i] = Math.min(Math.min(nums[i-1], f[i-1]*nums[i-1]), g[i-1]*nums[i-1]);
        }

        int ret = f[1];
        for(int i = 1; i<=n; i++) {
            ret = Math.max(ret,f[i]);
        }

        return ret;
    }
}

/*
f[i]: 以第i个元素为结尾, 乘积为正数的最小值
g[i]: 以第i个元素为结尾, 乘积为负数的最小值
nums[i] >= 0 :
f[i] = Math.max(f[i-1]*nums[i], nums[i]);
g[i] = Math.min(g[i-1]*nums[i], nums[i]);
nums[i] < 0:
f[i] = Math.max(g[i-1]*nums[i], nums[i]);
g[i] = Math.min(f[i-1]*nums[i], nums[i]); 
*/